// pages/index/productD/productD.js
const app = getApp();
import request from '../../utils/http.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectIndex: 0, //1分享登录  2 下单登录 3加入购物车登录
    title: ["商品描述","规格参数",],
    currentTab:0,


    code: '',
    phone: '',
    personId: 0,
    dianPuDengJi: 6,
    IsLogin: false,
    userInfo: {},
    hasUserInfo: false,
    // hiddenPopPaper: false, //微信授权


    width: 0,
    screenHeight: 0,
    winHeight:0,

    touXiangUrl: '',
    niCheng: '',
    tjr_id: 0,
    dianPuId: 0, //当前店铺ID
    login_dianPuId:0,//已登录店铺ID，用于判断需不需要重新登录


    productId: 0, //产品id
    chanPinMingCheng: '', //产品名称
    tuPianUrl: '', //产品封面
    xianShiJiaGe: 0, //原价
    shiJiJiaGe: 0, //实际销售价格
    huiYuanJiaGe:0,//会员价格
    guiGe: '', //显示规格
    yunFeiJiaGe: '', //运费价格
    yunFeiShuoMing: '', //邮寄说明
    yunFeiTxt: '',
    faHuoZhouQiShuoMing:'',
    chanPinShuoMing: '', //说明
    // keFu: '', //客服
    fuKuanRenShu: 0, //显示销售数量
    kuCun: 0, //库存
    jingXuanZhuangTai:1,
    reXiaoZhuangTai:1,

    CertifiCardList:[],//营业执照


    chanPinImageList: [],
    shiPinUrl: "",
    swiperListLength: 1,
    index: 1, //当前图片位置
    neiRong: '', //产品详情


    gouWuCheCount: 0, //购物车商品数量
    goumaiCount: 1, //直接购买产品数量
    qiGouShuLiang: 1, //最小起购数量


    gouMaible: false, //立即购买弹框
    shareble: false, //分享弹框
    raiseble:false,//众筹弹框
    increase: false, //服务对象信息添加
    hiddenSharePaper: true, //分享海报的弹框是否隐藏
    bottomViewble: false, //底部固定栏是否隐藏
    opacity: 0, //根据页面滚动位置，显示头部信息透明度
    shareFlag: false, //true 通过分享进入产品页面，需跳转店铺首页




    canvas: {},
    canvasWidth: 0,
    renderHeight: 0,
    canvasdestWidth: 0,
    canvasdestHeight: 0,

    SpLeiXing: 0,

    zxproductId: 0,

    guid_short:0,
    zslist: [],
    zslistLength: 0,

    keGouMaiShouLiang: 0, //可购买数量
    message: '', //提示信息


    xuNiZhuangTai: 0,

    yiShengList: [],
    yiShengListlength: 0,
    guidList: [], //会员开通人
    guidListLength: 0,
    guid: '',
    shopBuyerGuid:'',
    guidname:'',


    shangJiaStatus: 1, //是否上架: 1是 2否
    fenZuTitle: '', //产品分组
    MenuButtonTop: 50,
    MenuButtonHeight: 30,
    CustomBar: 60,


    userName: '', //联系人
    provinceName: '', //省
    cityName: '',
    countyName: '', //区
    detailInfo: '', //详细地址
    telNumber: '', //联系电话
    postalCode:'',
    nationalCode:'',
    zhongChouZhuangTai:'',//众筹状态

    jzrname: '', //就诊人姓名
    jzrsfz: '', //就诊人身份证号
    jzrphone: '', //就诊人手机号
    yjyToken:'',
  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var that = this

    wx.login({
      success: res => {
        that.setData({
          code: res.code
        })
      }
    })

    
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          screenHeight: res.screenHeight,
          width: res.screenWidth,
          winHeight: res.windowHeight - (390 / 750 * res.windowWidth),
        })
      }
    })


    that.setData({
      login_dianPuId:(wx.getStorageSync(app.globalData.SHOPID) == '' || wx.getStorageSync(app.globalData.SHOPID) == undefined) ? 1 : wx.getStorageSync(app.globalData.SHOPID),
      CustomBar: app.globalData.CustomBar,
      MenuButtonTop: app.globalData.MenuButtonTop,
      MenuButtonHeight: app.globalData.MenuButtonHeight,
      productId: options.productId,
      personId: wx.getStorageSync(app.globalData.PERSON_ID),
      phone:wx.getStorageSync(app.globalData.PHONENUMBER),

      dianPuId: (options.dianPuId == '' || options.dianPuId == undefined) ? ((wx.getStorageSync(app.globalData.SHOPID) == '' || wx.getStorageSync(app.globalData.SHOPID) == undefined) ? 1 : wx.getStorageSync(app.globalData.SHOPID)) : options.dianPuId,
      tjr_id: (options.tjr_id == '' || options.tjr_id == undefined) ? wx.getStorageSync(app.globalData.TJR_ID) : options.tjr_id,
      touXiangUrl: wx.getStorageSync(app.globalData.TouXiang),
      niCheng: wx.getStorageSync(app.globalData.NiCheng),
      shareFlag: (options.tjr_id == '' || options.tjr_id == undefined) ? false : true,

      userName: wx.getStorageSync(app.globalData.USERNAME), //联系人
      provinceName: wx.getStorageSync(app.globalData.PROVINCENAME), //省
      cityName: wx.getStorageSync(app.globalData.CITYNAME),
      countyName: wx.getStorageSync(app.globalData.COUNTYNAME), //区
      detailInfo: wx.getStorageSync(app.globalData.DETAILINFO), //详细地址
      telNumber: wx.getStorageSync(app.globalData.TELNUMBER), //联系电话
    })

    // wx.setStorageSync(app.globalData.LOGINSTATUS, that.data.IsLogin)



    if (options.scene) { //海报扫码
      let scene = decodeURIComponent(options.scene);

      console.log("scene:"+scene)

      that.setData({
        dianPuId: scene.split("_")[0],
        tjr_id: scene.split("_")[1],
        productId: scene.split("_")[2],
        guid_short:scene.split("_")[3]==''||scene.split("_")[3]==null?0:scene.split("_")[3],
        shareFlag: true
      })


    }
    wx.setStorageSync(app.globalData.SHOPID, that.data.dianPuId)
    wx.setStorageSync(app.globalData.TJR_ID, that.data.tjr_id)

    if(that.data.login_dianPuId==that.data.dianPuId && that.data.dianPuId>0){
      that.setData({
        IsLogin:wx.getStorageSync(app.globalData.LOGINSTATUS)==true?true:false,
      })

    }else{
      that.setData({
        IsLogin:false,
      })
    }
    that.getCertifiCard();//查询营业执照

    wx.setStorageSync(app.globalData.LOGINSTATUS, that.data.IsLogin)
  

  },

    /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 获取swipre高度，设置店铺信息和菜单固定位置

    if (this.data.IsLogin) {
      wx.showShareMenu({
        menus: ['shareAppMessage', 'shareTimeline']
      })
    } else {
      wx.hideShareMenu({
        menus: ['shareAppMessage', 'shareTimeline']
      })
    }

    this.getProductDetail();// 刷新购物车
  },


  //获取产品详情
  getProductDetail: function () {
    var that = this
    wx.showLoading({
      title: '产品加载中...',
      mask: true
    })
    let data = {
      productId: that.data.productId,
      personId: that.data.personId,
      dianPuId: that.data.dianPuId
    }
    request.get('product/productDetailInfo', data, res => {

      console.log("产品详情:" + JSON.stringify(res.data))

      that.setData({
        chanPinMingCheng: res.data.chanPinMingCheng,//产品名称
        tuPianUrl: res.data.tuPianUrl,//封面图
        xianShiJiaGe: res.data.xianShiJiaGe,//原价
        shiJiJiaGe: res.data.shiJiJiaGe,//销售价
        huiYuanJiaGe:res.data.huiYuanJiaGe,//会员价格
        kuCun: res.data.kuCun,//库存
        keGouMaiShouLiang:res.data.isHuiYuanKa==2?0:res.data.kuCun,//可购买数量,有的商品一次只能购买1份
        fuKuanRenShu: res.data.fuKuanRenShu,//付款人数、浏览人数
        guiGe: res.data.guiGe,//规格
        faHuoZhouQiShuoMing:res.data.faHuoZhouQiShuoMing,//发货说明
        chanPinShuoMing: res.data.chanPinShuoMing,//产品描述
        // keFu: res.data.keFu,//客服
       
        yunFeiJiaGe: res.data.yunFeiJiaGe,//运费价格
        yunFeiShuoMing: res.data.yunFeiShuoMing,//运费说明
        yunFeiTxt: (res.data.yunFeiJiaGe == 0 ? '包邮' : ((res.data.yunFeiJiaGe / 100).toFixed(2) + '元')) + (res.data.yunFeiShuoMing != '' ? (' | ' + res.data.yunFeiShuoMing) : ''),//运费描述

        shiPinUrl: res.data.shiPinUrl,//产品视频
        chanPinImageList: res.data.chanPinImageList,//产品轮播图
        swiperListLength: res.data.shiPinUrl == '' ? res.data.chanPinImageList.length : parseInt(res.data.chanPinImageList.length + 1),//轮播长度

        gouWuCheCount: res.data.gouWuCheCount,//购物车数量
        qiGouShuLiang: res.data.qiGouShuLiang,//起购数量
        goumaiCount:res.data.isHuiYuanKa==2?0:(res.data.gouWuCheCount > res.data.qiGouShuLiang ? res.data.gouWuCheCount : res.data.qiGouShuLiang),//默认显示起购数量

        yiShengList: res.data.yiShengList,//医生list
        yiShengListlength: res.data.yiShengList.length, // 医生数量

        xuNiZhuangTai: res.data.xuNiZhuangTai,//是否虚拟产品，虚拟产品不可以加入购物车 1普通商品 2 虚拟商品 
        isHuiYuanKa:res.data.isHuiYuanKa,//是否是会员卡，1普通商品，2是会员卡


        shangJiaStatus: res.data.shangJiaStatus,//当前产品是否在线销售，解决产品扫码进去显示内容
        fenZuTitle: res.data.fenZuTitle,// 产品所属分组

        jingXuanZhuangTai:res.data.jingXuanZhuangTai,//是否精选
        reXiaoZhuangTai:res.data.reXiaoZhuangTai,//是否热销

       

        zslist: res.data.zengPinList, //赠送商品列表  
        zslistLength: res.data.zengPinList == null ? 0 : res.data.zengPinList.length,
        zxproductId: (res.data.zengPinList.length > 0) ? res.data.zengPinList[0].productId : 0, //默认赠品ID

        zhongChouZhuangTai:res.data.zhongChouZhuangTai,//众筹状态


      })

      var html=res.data.neiRong.replace(/<img /g, "<img style='max-width:100%;height:auto;display:block;'")       
      var htmlS=html.replace(/style=""/g,'')

      that.setData({
        neiRong:htmlS
      })

      wx.hideLoading();


 
      if (res.data.isHuiYuanKa==2 ) {//是会员卡，获取guid
        // that.getJZpersonOne(that.data.guid_short)
        that.getToken_YJY()
      }



    }, err => {
      wx.hideLoading();
      wx.showToast({
        title: '查询失败！', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    })

  },


  //供应商营业执照
  getCertifiCard:function(){
    var that = this

    let data = {
      zhongXinChanPinId: that.data.productId,

    }
    request.get('product/getProductGongYingShangZiZhi', data, res => {

      // console.log("营业执照:" + JSON.stringify(res.data))

      if(res.data.length>0){
        that.data.title.push("商家")
        that.setData({
          title:that.data.title,
          CertifiCardList:res.data
        })
      }



    }, err => {

      wx.showToast({
        title: '查询失败！', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    })
  },

  //获取我已关联的就诊人list
  // getJZPersonList:function(){
  //   var that = this
  //   wx.showLoading({
  //     title: '关联就诊人查询中...',
  //     mask: true
  //   })

  //   request.get('jianKangDangAn/xiaJiList', null, res => {
  //     console.log("就诊人:" + JSON.stringify(res.data))
  //     that.setData({

  //       guidList: res.data, //就诊人 
  //       guidListLength: res.data == null ? 0 : res.data.length,
  //     })

  //     wx.hideLoading();
  //   }, err => {
  //     wx.hideLoading();
  //     wx.showToast({
  //       title: '获取信息失败', // 提示的内容
  //       icon: "none", // 图标，默认success
  //       duration: 1000, // 提示的延迟时间，默认1500
  //       mask: false, // 是否显示透明蒙层，防止触摸穿透
  //     })
  //   })

  // },

    //短guid，获取正常就诊人
  // getJZpersonOne: function (guid_short) {
  //     var that = this
  //     let data = {
  //       jiuZhenRenGUID:guid_short
  //     }
  //     wx.showLoading({
  //       title: '就诊人查询中...',
  //       mask: true
  //     })
  
  //     request.get('product/huiYuanShortChangToeLong', data, res => {
  //       console.log("获取一个就诊人:" + JSON.stringify(res.data))
  //         that.setData({
  //           guidList: res.data, //就诊人 
  //           guidListLength: res.data == null ? 0 : res.data.length,
  //         })
  //       wx.hideLoading();
  //     }, err => {
  //       wx.hideLoading();
  //       wx.showToast({
  //         title: '获取信息失败', // 提示的内容
  //         icon: "none", // 图标，默认success
  //         duration: 1000, // 提示的延迟时间，默认1500
  //         mask: false, // 是否显示透明蒙层，防止触摸穿透
  //       })
  //     })
  
  // },
  
  //获取医加医外部token
  getToken_YJY: function () {
    var that = this;
    wx.request({
      url: app.globalData.base_yjy_url + 'lo/GetToken',
      method: 'POST',
      data: {
        id: '11001002',
        password: '763986',
      },
      success: function (res) {
        console.log("获取医加医token:" + JSON.stringify(res))
        if(res.data.code==1){
          that.setData({
            yjyToken:res.data.data.token
          })
          
          if(that.data.guid_short>0){
            that.getJZR_YJY('',that.data.guid_short)
          }else if(that.data.phone!=''){
            that.getJZR_YJY(that.data.phone,'')
          }

        }else{
          wx.showToast({
            title: '获取token失败', // 提示的内容
            icon: "none", // 图标，默认success
            duration: 3000, // 提示的延迟时间，默认1500
            mask: false, // 是否显示透明蒙层，防止触摸穿透
          })
        }

      },
      fail: function (err) {

        wx.showToast({
          title: '获取token失败', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 3000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      },
      complete: function (res) {

      }
    })
  },


  //根据手机号，或者短GUId，获取就诊人list
  getJZR_YJY:function(phone,guid_short){
    var that = this;
    wx.request({
      url: app.globalData.base_yjy_url + 'robot/queryBuyer',
      method: 'POST',
      header: {
        'token':that.data.yjyToken,  
      },
      data: {
        phone: phone,
        patientId: guid_short,
      },
      success: function (res) {
        console.log("就诊人:" + JSON.stringify(res))
        if(res.data.code==1){
          that.setData({
            guidList:res.data.data,
            guidListLength: res.data.data== null ? 0 : res.data.data.length,
          })
        }

      },
      fail: function (err) {

        wx.showToast({
          title: '获取就诊人失败', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 3000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      },
      complete: function (res) {

      }
    })
  },
  
  //添加就诊人
  addJZR_YJY:function(){
    var that = this;
    wx.showLoading({
      title: '处理中...',
      mask: true
    })
    wx.request({
      url: app.globalData.base_yjy_url + 'robot/newBuyer',
      method: 'POST',
      header: {
        'token':that.data.yjyToken,  
      },
      data: {
        name: that.data.jzrname,
        idcard:that.data.jzrsfz,
        patientPhone:that.data.jzrphone,
        buyPhone:that.data.phone,
        shopid:that.data.dianPuId

      },
      success: function (res) {
        console.log("添加就诊人:" + JSON.stringify(res))
        if(res.data.code==1){
          that.getJZR_YJY(that.data.phone,'')
          that.setData({
            jzrname:'',
            jzrsfz:'',
            jzrphone:'',
        
            gouMaible: true,
            bottomViewble: false,
            increase: false,
          })
        }else{
          var mess=res.data.message
          wx.showToast({
            title: mess, // 提示的内容
            icon: "none", // 图标，默认success
            duration: 3000, // 提示的延迟时间，默认1500
            mask: false, // 是否显示透明蒙层，防止触摸穿透
          })
        }
        wx.hideLoading();

      },
      fail: function (err) {
        wx.hideLoading();
        wx.showToast({
          title: '添加就诊人失败', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 3000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      },
      complete: function (res) {

      }
    })
  },


    //判断就诊人购买资格
  getJZpersonInfo: function (guid) {
      var that = this
      let data = {
        productId: that.data.productId,
        jiuZhenRenGUID:guid
      }
      wx.showLoading({
        title: '分析中...',
        mask: true
      })
  
      request.get('product/isHuiYuanZiGE', data, res => {
        console.log("判断购买资格:" + JSON.stringify(res.data))
        wx.hideLoading();
        //判断购买资格
        that.setData({
          keGouMaiShouLiang:res.data.status==1?1:0, //普通商品由商城后台定，VIP由机器人端定
          goumaiCount: res.data.status==1?1:0,
          message: res.data.status==2?'请先实名认证':(res.data.status==3?'您已购买当前会员':'')
        })

        if( res.data.status!=1){
          wx.showToast({
            title: that.data.message, // 提示的内容
            icon: "none", // 图标，默认success
            duration: 3000, // 提示的延迟时间，默认1500
            mask: false, // 是否显示透明蒙层，防止触摸穿透
          })
        }
  
  
  
     
      }, err => {
        wx.hideLoading();
        wx.showToast({
          title: '获取信息失败', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 1000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      })
  
  },
  

  
  //产品分组切换

  onTabsChange(e){
    // console.log("value:" + e.detail.value)
    this.setData({
      currentTab:e.detail.value
    })
  },

   // 点击标题切换当前页时改变样式
   swichNav: function (e) {
    //  console.log("节点:" + JSON.stringify(e))
   
     let index = e.detail.current
    //  console.log("current:" + index)
    if (this.data.currentTab == index) {
      return false;
    } else {
      this.setData({
        currentTab: index
      })
    }
  },



  //会员绑定
  radioChange(e) {
    console.log('绑定会员id：', e.detail.value)
    this.setData({
      guid: this.data.guidList[e.detail.value].patient_unique_guid,
      guidname:this.data.guidList[e.detail.value].name,
      shopBuyerGuid: this.data.guidList[e.detail.value].shopBuyerGuid,
    })

    this.getJZpersonInfo(this.data.guid)
  },


  //购买
  gouMaibind: function (e) {
    var that = this
    if (that.data.IsLogin) { //登录了
      if (that.data.gouMaible) { //第二次点立即购买
        if (that.data.goumaiCount > 0) { //有可购买的商品
          if (that.data.isHuiYuanKa == 2 && (that.data.guid == '0' ||that.data.guid =='')) {
            wx.showToast({
              title: '请选择要绑定的用户', // 提示的内容
              icon: "none", // 图标，默认success
              duration: 1000, // 提示的延迟时间，默认1500
              mask: false, // 是否显示透明蒙层，防止触摸穿透
            })

          } else {
            that.setData({
              gouMaible: !that.data.gouMaible
            })
            wx.navigateTo({
              url: '/pages/orders_queren/orders_queren?type=2&productId=' + that.data.productId + '&goumaiCount=' + that.data.goumaiCount + '&zengSongChanPinId=' + that.data.zxproductId + '&guid=' + that.data.guid,
            })
          }
        } else { //部分会员商品无法重复购买

          var mess=that.data.message==''?'购买数量不能为0':that.data.message

          wx.showToast({
            title: mess, // 提示的内容
            icon: "none", // 图标，默认success
            duration: 1000, // 提示的延迟时间，默认1500
            mask: false, // 是否显示透明蒙层，防止触摸穿透
          })

        }

      } else { //第一次点立即购买


          that.setData({
            gouMaible: !that.data.gouMaible
          })
        

      }
    } else { //未登录，添加到临时全局gwcList
      that.setData({
        selectIndex: 2
      })
      that.toLogin()
    }
  },
  
  
  //点击显示弹框
  pickShare() {

    if (this.data.IsLogin) {
      this.setData({
        shareble: true,
        bottomViewble: true,
      })
    } else {
      wx.showToast({
        title: '请先登录', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })

    }
  },

//点击显示添加服务对象信息弹框
increase() {
  this.setData({
    increase: true,
    bottomViewble: true,
    gouMaible: false,
  })
},

//点击关闭添加服务对象信息弹框
increasefalse() {
  this.setData({
    increase: false,
    bottomViewble: false,
    // isRead: false,
    gouMaible:true
  })
},

pop_up: function () {
  var that = this;
  // 验证姓名是否为空
  if (that.data.jzrname === '') {
    wx.showToast({
      title: '姓名不能为空!!!',
      icon: "none",
      duration: 2000,
      mask: false,
    });
    return; // 如果姓名为空，则不再继续后续验证和操作
  }
  // 验证身份证号是否为空及长度是否为18位
  if (!that.data.jzrsfz || that.data.jzrsfz.length !== 18) {
    let errMsg = that.data.jzrsfz ? '请输入正确的身份证号' : '身份证号不能为空';
    wx.showToast({
      title: errMsg,
      icon: "none",
      duration: 2000,
      mask: false,
    });
    return;
  }

  if (!that.data.jzrphone || that.data.jzrphone.length !== 11) {
    let errMsg = that.data.jzrphone ? '请输入正确的手机号' : '手机号不能为空';
    wx.showToast({
      title: errMsg,
      icon: "none",
      duration: 2000,
      mask: false,
    });
    return;
  }
  // 身份证号验证通过后，显示确认提交模态框
  wx.showModal({
    title: '提交确认',
    content: '是否确定提交',
    showCancel: true,
    cancelText: '取消',
    confirmText: '确定',
    success: function (res) {
      if (res.confirm) {
        that.setData({
         
        });
        that.addJZR_YJY();
      } else if (res.cancel) {
        that.increasefalse();
        return;
      }
    },
  });
},

  // 关闭分享弹框
  colseShare: function () {
    this.setData({
      shareble: false,
      bottomViewble: false,

    })
  },


  //关闭购买数量设置
  closeGoumai(e) {
    this.setData({
      gouMaible: false,
      raiseble:false,
      bottomViewble:false
    })
  },

  //获取滚动条位置，当到固定值时，固定店铺信息和菜单栏
  onPageScroll: function (e) {
    this.setData({
      opacity: e.scrollTop / this.data.width > 1 ? 1 : e.scrollTop / this.data.width
    })
  },


  //添加购物车
  addshopcar: function () {
    var that = this

      let data = {
        zhongXinProductId: that.data.productId,
        personId: that.data.personId,
        dianPuId: that.data.dianPuId,
        flag: 1, //增加
        zengSongChanPinId:that.data.zxproductId
      }
      request.get('gouWuChe/addReduce', data, res => {
        // console.log("添加购物车:" + JSON.stringify(res.data))
        var mesage = res.data.message
        wx.showToast({
          title: mesage, // 提示的内容
          icon: "none", // 图标，默认success
          duration: 1000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
        if (res.data.status == 1) {
          that.setData({
            gouWuCheCount: this.data.gouWuCheCount + 1,
            goumaiCount:this.data.gouWuCheCount + 1,
          })
        } else if (res.data.status == 2) {
          that.setData({
            gouWuCheCount: this.data.gouWuCheCount - 1,
            goumaiCount:this.data.gouWuCheCount - 1,
          })

        }

      })
 

  },

  //直接购买——添加数量
  bindAddTap: function () {

    if (this.data.goumaiCount < this.data.keGouMaiShouLiang) {
      this.setData({
        goumaiCount: this.data.goumaiCount + 1
      })
    } else {
      wx.showToast({
        title: '超出最大可购买数量', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 2000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    }


  },

  //直接购买——减少数量
  bindReduceTap: function () {
    if (this.data.goumaiCount > this.data.qiGouShuLiang) {
      this.setData({
        goumaiCount: this.data.goumaiCount - 1
      })
    }
  },

  //轮播图index
  currentAction: function (e) {
    // console.log(e.detail.current)
    this.setData({
      index: e.detail.current + 1
    })
  },




  //返回
  bindNavigateBack: function () {
    if (this.data.shareFlag == true) {
      wx.switchTab({
        url: '/pages/shop/shop',
      })
    } else {
      wx.navigateBack({
        delta: 1
      })
    }
  },


  //跳转购物车
  bindToGWC: function () {
    wx.navigateTo({
      url: '/pages/gouwc/gouwc',
    })

  },


  //跳转首页
  bindToIndex: function () {
    wx.switchTab({
      url: '/pages/index/index',
    })

  },


  //众筹
  bindToRaise:function(){
    if (this.data.IsLogin) {
      this.setData({
        raiseble: true,
        bottomViewble: true,
      })
    } else {
      wx.showToast({
        title: '请先登录', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })

    }
  },

   //发起众筹
   bindToRaiseStart:function(){
     console.log("发起众筹")
     if(this.data.userName!==''||this.data.provinceName!==''||this.data.cityName!==''||this.data.countyName!==''||this.data.detailInfo!==''||this.data.telNumber!==''){
      this.getgenerateZc()
      this.closeGoumai();
     }else{
      wx.showToast({
        title: "收货地址不能为空！", // 提示的内容
        icon: "none", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
     }

  },

   //选择地址
   setAderssTap: function () {
    var that = this
    if (wx.chooseAddress) {
      wx.chooseAddress({
        success: function (res) {
          wx.setStorageSync(app.globalData.USERNAME, res.userName);
          wx.setStorageSync(app.globalData.PROVINCENAME, res.provinceName);
          wx.setStorageSync(app.globalData.CITYNAME, res.cityName);
          wx.setStorageSync(app.globalData.COUNTYNAME, res.countyName);
          wx.setStorageSync(app.globalData.DETAILINFO, res.detailInfo);
          wx.setStorageSync(app.globalData.TELNUMBER, res.telNumber);
          wx.setStorageSync(app.globalData.NATIONALCODE, res.nationalCode);
          wx.setStorageSync(app.globalData.POSTALCODE, res.postalCode);
          that.setData({
            userName: res.userName,
            provinceName: res.provinceName,
            cityName: res.cityName,
            countyName: res.countyName,
            detailInfo: res.detailInfo,
            telNumber: res.telNumber,
            nationalCode: res.nationalCode,
            postalCode: res.postalCode,
          })
        },
        fail: function () {


          wx.openSetting({
            success: (res) => {
              if (res.authSetting["scope.address"]) { ////如果用户重新同意了授权
                wx.chooseAddress({
                  success: function (ress) {
                    wx.setStorageSync(app.globalData.USERNAME, ress.userName);
                    wx.setStorageSync(app.globalData.PROVINCENAME, ress.provinceName);
                    wx.setStorageSync(app.globalData.CITYNAME, ress.cityName);
                    wx.setStorageSync(app.globalData.COUNTYNAME, ress.countyName);
                    wx.setStorageSync(app.globalData.DETAILINFO, ress.detailInfo);
                    wx.setStorageSync(app.globalData.TELNUMBER, ress.telNumber);
                    wx.setStorageSync(app.globalData.NATIONALCODE, ress.nationalCode);
                    wx.setStorageSync(app.globalData.POSTALCODE, ress.postalCode);
                    that.setData({
                      userName: ress.userName,
                      provinceName: ress.provinceName,
                      cityName: ress.cityName,
                      countyName: ress.countyName,
                      detailInfo: ress.detailInfo,
                      telNumber: ress.telNumber,
                      nationalCode: ress.nationalCode,
                      postalCode: ress.postalCode,
                    })

                  },
                })
              }
            }
          })
        }
      })
    } else {
      console.log('当前微信版本不支持chooseAddress');
    }

    // wx.chooseInvoiceTitle({
    //     success(res) {
    //          console.log("发票:"+JSON.stringify(res))
    //     }
    // })
  },

   //生成众筹
   getgenerateZc: function () {
    var that = this
    let data = {
      chanPinId: that.data.productId,
      chanPinLeiXing:1,
      patientUniqueGuid:'',
      fenShu: that.data.goumaiCount,
      dianPuId: that.data.dianPuId,
      wxUserName:that.data.userName,
      wxPostalCode:that.data.postalCode,
      wxProvinceName:that.data.provinceName,
      wxCityName:that.data.cityName,
      wxCountyName:that.data.countyName,
      wxDetailInfo:that.data.detailInfo,
      wxNationalCode:that.data.nationalCode,
      wxTelNumber:that.data.telNumber
    }
    // console.log(data)
    request.get('zhongChou/addOneZhongChou', data, res => {
      wx.hideLoading();
      // console.log("众筹订单id:" + JSON.stringify(res))
      if(res.statusCode==200){
        wx.navigateTo({
          url: '/pages/raiseInfo/raiseInfo?zhongChouOrderFormId='+res.data.zhongChouOrderFormId
        })
        
      }else{
        wx.showToast({
          title: '众筹发起失败', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 1000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
      }
    }, err => {
      wx.hideLoading();
      wx.showToast({
        title: '生成失败！', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    })
  
  },

  //分享产品
  onShareAppMessage: function (res) {
    var that = this;
    that.setData({
      shareble: false
    })

    if (that.data.IsLogin) {
      return {
        title: that.data.chanPinMingCheng,
        path: '/pages/productInfo/productInfo?dianPuId=' + that.data.dianPuId + '&&productId=' + that.data.productId + '&&tjr_id=' + that.data.personId,
        imageUrl: that.data.tuPianUrl
      }
    } else {
      wx.showToast({
        title: '请先登录！', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    }
  },


  //海报关闭
  bindClosePaper: function () {
    this.setData({
      hiddenSharePaper: !this.data.hiddenSharePaper,
      bottomViewble: !this.data.bottomViewble
    })
  },

  //产品生成海报
  bindProTap: function (e) {
    wx.showLoading({
      title: '海报生成中...',
    })
    var that = this
    that.setData({
      shareble: false
    })
    that.getWechatCode(that.data.tuPianUrl);
  },

  //获取微信二维码(用于链接)
  getWechatCode: function (paperUrl) {
    var that = this
    var sceneStr = that.data.dianPuId + '_' + that.data.personId + '_' + that.data.productId
    //console.log("sceneStr：" + sceneStr)
    wx.request({
      url: app.globalData.base_url + 'resource/getQRAndUpToQiNiu',
      data: {
        id: that.data.productId,
        dianPuId: that.data.dianPuId,
        leiXing: 2, //1人的二维码，2产品的二维码
        path: "pages/productInfo/productInfo",
        scene: sceneStr
      },
      success: function (res) {
        // console.log("wxerWeiMaUrl:" + JSON.stringify(res.data))
        var wxerWeiMaUrl = res.data.WXErWeiMaUrl;
        that.createProImg(paperUrl, wxerWeiMaUrl, that.data.touXiangUrl);
      }
    })
  },


  //绘制海报
  createProImg: function (paperUrl, wxerWeiMaUrl, touXiangUrl) {
    this.setData({
      hiddenSharePaper: !this.data.hiddenSharePaper
    })

    wx.hideLoading();
    wx.createSelectorQuery()
      .select('#myCanvas') // 在 WXML 中填入的 id
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {

        // console.log("画图:" + JSON.stringify(res))

        const canvas = res[0].node
        // Canvas 画布的实际绘制宽高
        const renderWidth = res[0].width
        const renderHeight = res[0].height
        // console.log(renderWidth)
        // Canvas 绘制上下文
        const ctx = canvas.getContext('2d')

        // 初始化画布大小
        const dpr = wx.getWindowInfo().pixelRatio
        // console.log("dpr:" + dpr)
        canvas.width = renderWidth * dpr
        canvas.height = renderHeight * dpr

        var scale = (renderWidth / 580) * dpr;

        this.setData({
          canvas: canvas,
          canvasWidth: renderWidth,
          renderHeight: renderHeight,
          canvasdestWidth: renderWidth * dpr,
          canvasdestHeight: renderHeight * dpr,
        })

        // ctx.scale(dpr, dpr)

        ctx.fillStyle = "white";
        ctx.fillRect(0, 0, 580 * scale, 920 * scale);



        ctx.beginPath();
        ctx.lineWidth = "1";
        ctx.strokeStyle = "rgb(220,220,220)"; // Green path
        ctx.moveTo(0, 760 * scale);
        ctx.lineTo(580 * scale, 760 * scale);
        ctx.stroke(); // Draw it

        //画主图      
        const imageMain = canvas.createImage();
        imageMain.src = paperUrl;
        imageMain.onload = () => {
          ctx.drawImage(imageMain, 10 * scale, 10 * scale, 560 * scale, 560 * scale)

        }

        var priceIconSize = 28 * scale
        var priceIconSizestr = priceIconSize + 'px Arial'

        //价格

        let shiJiJiaGeICON = {
          x: 16 * scale,
          y: 610 * scale,
          color: '#f92b3a',
          size: priceIconSizestr,
          align: 'left',
          baseline: 'top',
          text: '￥',
          bold: false,
          maxWidth:540 * scale
        };
        this.drawText(ctx, shiJiJiaGeICON);


        var priceSize = 40 * scale
        var priceSizestr = priceSize + 'px Arial'

        let shiJiJiaGe = {
          x: 50 * scale,
          y: 600 * scale,
          color: '#f92b3a',
          size: priceSizestr,
          align: 'left',
          baseline: 'top',
          text: this.data.shiJiJiaGe / 100,
          bold: true,
          maxWidth:540 * scale
        };
        this.drawText(ctx, shiJiJiaGe);

        //产品名称
        var productNameSize = 30 * scale
        var productNameSizestr = productNameSize + 'px Arial'

        if (this.data.chanPinMingCheng.length > 40) {
          var proName1 = this.data.chanPinMingCheng.substring(0, 20)


          let proName1Cont = {
            x: 16 * scale,
            y: 660 * scale,
            color: '#474646',
            size: productNameSizestr,
            align: 'left',
            baseline: 'top',
            text: proName1,
            bold: false,
            maxWidth:540 * scale
          };
          this.drawText(ctx, proName1Cont);


          var proName2 = this.data.chanPinMingCheng.substring(20, 40) + '...'

          let proName2Cont = {
            x: 16 * scale,
            y: 700 * scale,
            color: '#474646',
            size: productNameSizestr,
            align: 'left',
            baseline: 'top',
            text: proName2,
            bold: false,
            maxWidth:540 * scale
          };
          this.drawText(ctx, proName2Cont);

        } else if (this.data.chanPinMingCheng.length < 40 && this.data.chanPinMingCheng.length > 20) {
          var proName1 = this.data.chanPinMingCheng.substring(0, 20)
          let proName1Cont = {
            x: 16 * scale,
            y: 660 * scale,
            color: '#474646',
            size: productNameSizestr,
            align: 'left',
            baseline: 'top',
            text: proName1,
            bold: false,
            maxWidth:540 * scale
          };
          this.drawText(ctx, proName1Cont);

          var proName2 = this.data.chanPinMingCheng.substring(20, this.data.chanPinMingCheng.length)
          let proName2Cont = {
            x: 16 * scale,
            y: 704 * scale,
            color: '#474646',
            size: productNameSizestr,
            align: 'left',
            baseline: 'top',
            text: proName2,
            bold: false,
            maxWidth:540 * scale
          };
          this.drawText(ctx, proName2Cont);

        } else {
          //画产品名称
          let chanPinMingCheng = {
            x: 16 * scale,
            y: 660 * scale,
            color: '#474646',
            size: productNameSizestr,
            align: 'left',
            baseline: 'top',
            text: this.data.chanPinMingCheng,
            bold: false,
            maxWidth:540 * scale
          };
          this.drawText(ctx, chanPinMingCheng);
        }



        ctx.save()
        //画二维码        
        const imageCode = canvas.createImage();
        imageCode.src = wxerWeiMaUrl;
        imageCode.onload = () => {
          ctx.drawImage(imageCode, 400 * scale, 770 * scale, 140 * scale, 140 * scale)

        }



        //画推荐人头像      
        const imageTouX = canvas.createImage();
        imageTouX.src = touXiangUrl;
        imageTouX.onload = () => {
          // 将图片绘制到 canvas 上
          ctx.save()
          ctx.beginPath(); //开始绘制
          // ctx.strokeStyle="white"
          ctx.arc(80 * scale, 840 * scale, 50 * scale, 0, Math.PI * 2, false);
          // ctx.stroke();
          ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
          ctx.drawImage(imageTouX, 30 * scale, 790 * scale, 100 * scale, 100 * scale)
          ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制

        }

        var tjrNameSize = 28 * scale
        var tjrNameSizestr = tjrNameSize + 'px Arial'

        //推荐人昵称
        let userName = {
          x: 144 * scale,
          y: 838 * scale,
          color: '#838080',
          size: tjrNameSizestr,
          align: 'left',
          baseline: 'bottom',
          text: this.data.niCheng,
          bold: false,
          maxWidth:220 * scale
        };
        this.drawText(ctx, userName);

        //推荐说明
        var tjrSMSize = 20 * scale
        var tjrSMSizestr = tjrSMSize + 'px Arial'

        let tjContent = {
          x: 144 * scale,
          y: 850 * scale,
          color: '#b3b3b3',
          size: tjrSMSizestr,
          align: 'left',
          baseline: 'top',
          text: '为您推荐',
          bold: false,
          maxWidth:220 * scale
        };
        this.drawText(ctx, tjContent);


      })



  },


  drawText: function (ctx, obj) {
    ctx.save();
    ctx.fillStyle = obj.color;
    // ctx.setFontSize(obj.size);
    ctx.font = obj.size;
    // ctx.setTextAlign(obj.align);
    ctx.textAlign = obj.align;
    // ctx.setTextBaseline(obj.baseline);
    ctx.textBaseline = obj.baseline;

    // ctx.font="20px Georgia";
    // ctx.fillText(obj.text, obj.x,obj.y);

    if (obj.bold) {
      ctx.fillText(obj.text, obj.x, obj.y - 0.5,obj.maxWidth);
      ctx.fillText(obj.text, obj.x - 0.5, obj.y,obj.maxWidth);
    }
    ctx.fillText(obj.text, obj.x, obj.y,obj.maxWidth);
    if (obj.bold) {
      ctx.fillText(obj.text, obj.x, obj.y + 0.5,obj.maxWidth);
      ctx.fillText(obj.text, obj.x + 0.5, obj.y,obj.maxWidth);
    }
    ctx.restore();
  },


  //保存图片权限判断
  isgetPower: function () {

    var that = this
    wx.getSetting({
      success(res) {
        if (['scope.writePhotosAlbum'] in res.authSetting) {
          // 如果授权过且同意了
          if (res.authSetting[`scope.writePhotosAlbum`]) {
            that.bindSavePaper()
          } else {
            wx.showModal({
              title: "请求授权相册存储",
              content: "需要获取您的相册存储权限，请确认授权",
              success: res => {
                if (res.confirm) {
                  wx.openSetting({
                    success: res => {
                      that.bindSavePaper()
                      console.log(res)
                    },
                    fail: err => {
                      console.log(err)
                    }
                  })
                } else if (res.cancel) {
                  console.log("你又取消了")
                }
              }
            })
          }
        } else {
          that.bindSavePaper()
        }
      }
    })




  },

  //保存图片到相册
  bindSavePaper: function () {
    wx.showLoading({
      title: '生成中...',
    })

    // var that = this

    wx.canvasToTempFilePath({
      canvas: this.data.canvas,
      x: 0,
      y: 0,
      width: this.data.canvasWidth,
      height: this.data.canvasHeight,
      destWidth: this.data.canvasdestWidth,
      destHeight: this.data.canvasdestHeight,
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: res => {
            // console.log(this.saveTempFilePath)
            wx.showModal({
              title: "保存成功！",
              content: "图片已保存到本地相册",
              showCancel: false,
              success(res) {

              }
            })
          },
          fail: err => {
            console.log(err)
          }
        })
      },
      fail: err => {
        console.log(err)
      }
    })
    setTimeout(() => {
      wx.hideLoading()
    }, 1000)


  },


  //V3.0 获取手机号码
  getPhoneNumber: function (e) {
    var that = this
    if (e.detail.errMsg == "getPhoneNumber:ok") { //允许
      that.decryptPhone(e);
    } else { //拒绝
      wx.showToast({
        title: "请授权！！", // 提示的内容
        icon: "none", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    }
  },


   //V3.0 解密手机号码
  decryptPhone: function (e) {

    wx.showLoading({
      title: '解析中...',
      mask: true
    })

    var that = this;
    let code=that.data.code;
    let iv = e.detail.iv;
    let encryptedData = e.detail.encryptedData;

    wx.request({
      url: app.globalData.base_url + 'resource/getWXPhoneDirect',
      data: {
        iv: iv,
        js_code:code,
        encrypted: encryptedData,
        tuiJianRenId:that.data.tjr_id,
        dianPuId:that.data.dianPuId
      },
      success: function (res) {
       console.log("解密手机号码:" + JSON.stringify(res.data))
       
        if(res.data.purePhoneNumber=='' || res.data.status==500){

          wx.showToast({
            title: '解析异常，右上角重新进入小程序', // 提示的内容
            icon: "none", // 图标，默认success
            duration: 3000, // 提示的延迟时间，默认1500
            mask: false, // 是否显示透明蒙层，防止触摸穿透
          })

        }else{
          wx.setStorageSync(app.globalData.OPENID, res.data.openId)
          wx.setStorageSync(app.globalData.PERSON_ID, res.data.personId)
          wx.setStorageSync(app.globalData.TOKEN, res.data.token)
          wx.setStorageSync(app.globalData.PHONENUMBER, res.data.purePhoneNumber)
          wx.setStorageSync(app.globalData.LOGINSTATUS, true)
          wx.setStorageSync(app.globalData.NiCheng, res.data.niCheng)
          wx.setStorageSync(app.globalData.TouXiang, res.data.touXiangUrl)


          that.syncData(res.data.token)
          that.setData({    
            personId: res.data.personId,
            IsLogin:true,
            touXiangUrl: res.data.touXiangUrl,
            niCheng: res.data.niCheng,  
            phone:res.data.purePhoneNumber
          })

          // 会员卡产品，并且不是扫码进来的，需要获取我的健康档案list
          if(that.data.isHuiYuanKa==2){
            that.getToken_YJY()
          }

        }

        if (that.data.selectIndex == 1) {
          that.setData({
            shareble: true,
            bottomViewble: true,
          })
        }

        if (that.data.selectIndex == 2) {
          that.gouMaibind()
        }

        if (that.data.selectIndex == 3) {
          that.addshopcar()
        }
      },
      fail: function (err) {
        that.setData({
          IsLogin:false
        })
        wx.showToast({
          title: '获取数据失败,请检查网络', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 3000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      },
      complete: function (res) {
        wx.hideLoading();
      }
    })
  },

  
  //登录同步健康数据
  syncData(token){


      wx.request({
        url: app.globalData.base_url + 'qiTa/tongBuJiuZhenRenAndGouMaiChanPin',
        header: {
          'token':token,  
        },
        success: function (res) {
          console.log("同步数据成功" )
        },
        fail: function (err) {
          console.log("同步数据失败" )
        },
        complete: function (res) {
          console.log("同步数据完成" )
          
        }
      })


  },

  //协议
  bindXieyiTap: function () {
    wx.navigateTo({
      url: '/pkg_wo/pages/xieyiInfo/xieyiInfo',
    })

  },

  //赠品类别
  Typeswitch: function (e) {
    var that = this

      if (that.data.zxproductId != e.currentTarget.dataset.id) {
      //   wx.showToast({
      //     title: '您已取消赠品', // 提示的内容
      //     icon: "none", // 图标，默认success
      //     duration: 1000, // 提示的延迟时间，默认1500
      //     mask: false, // 是否显示透明蒙层，防止触摸穿透
      //   })
      //   that.setData({
      //     zxproductId: 0,
      //   })

      // } else {
        that.setData({
          zxproductId: e.currentTarget.dataset.id,
        })
      }

  },

  preview(e) {   
     let index = e.currentTarget.dataset.index   
     wx.previewImage({
      urls: this.data.CertifiCardList, //需要预览的图片http链接列表，注意是数组
      current: index, // 当前显示图片的http链接，默认是第一个
      success: function (res) {},
      fail: function (res) {},
      complete: function (res) {},
    })
 },


  
  //跳转医师详情
  doctortap: function (e) {
    var ysid = e.currentTarget.dataset.id;
    console.log(ysid)
    wx.navigateTo({
      url: '/pkg_doctors/pages/doctor/doctor?ysid=' + ysid,
    })
  },


  ts: function () {
    wx.showToast({
      title: '虚拟产品暂不支持加入购物车', // 提示的内容
      icon: "none", // 图标，默认success
      duration: 2000, // 提示的延迟时间，默认1500
      mask: false, // 是否显示透明蒙层，防止触摸穿透
    })
  },

   //添加姓名
   bindNameInput: function (e) {
    this.setData({
      jzrname: e.detail.value
    })
  },

  
  //添加就诊人手机号
  bindPhoneInput: function (e) {
    this.setData({
      jzrphone: e.detail.value
    })
  },

  //添加身份证号码
  bindsfzInput: function (e) {
    this.setData({
      jzrsfz: e.detail.value
    })
  },


})